{% extends "base.html" %}
{% block breadcrumb_current %}
    库存管理 > 出入库申请
{% endblock %}
{% block content %}

    {% if messages %}
        {% for message in messages %}
            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% endfor %}
    {% endif %}

    <div class="bg-light p-3 shadow-sm">
        <h5 style="color: #417690;">
            {{ inventory.warehouse.warehouse }}--{{ inventory.material.material }}： <span id="current_quantity">{{ inventory.quantity }}</span> {{ inventory.material.measureunit }}
            <a href="{% url 'inventory_list' %}" class="btn btn-secondary btn-sm float-end">库存物料</a></h5>
        </div>
    <div>

<div class="container mt-4">
    <div class="card" style="margin-top: 50px;">
        <div class="card-body">

        <form method="post" id="recordForm">
            {% csrf_token %}
            <input type="hidden" name="inventory" value="{{ inventory.id }}">

            <div class="row">
                <div class="col-md-2 mb-3 mx-auto" style="margin-top: 30px;">
                    <label for="{{ form.operatemode.id_for_label }}" class="form-label">操作类型<span class="text-danger">*</span></label>
                    <select name="{{ form.operatemode.name }}" id="{{ form.operatemode.id_for_label }}"
                            class="form-control {% if form.operatemode.errors %}is-invalid{% endif %}">
                        {% for choice in form.operatemode.field.choices %}
                            {% if choice.0 != 'transfer_in' %}
                                <option value="{{ choice.0 }}" {% if form.operatemode.value == choice.0 %}selected{% endif %}>
                                    {{ choice.1 }}
                                </option>
                            {% endif %}
                        {% endfor %}
                    </select>
                    {% if form.operatemode.errors %}
                        <div class="invalid-feedback">{{ form.operatemode.errors|join:", " }}</div>
                    {% endif %}
                </div>

                <div class="col-md-2 mb-3 mx-auto" style="margin-top: 30px;">
                    <label for="{{ form.quantity.id_for_label }}" class="form-label">数量<span class="text-danger">*</span></label>
                    <input type="number" name="{{ form.quantity.name }}" id="{{ form.quantity.id_for_label }}"
                           value="{{ form.quantity.value|default:'' }}"
                           class="form-control {% if form.quantity.errors %}is-invalid{% endif %}" min="1">
                    {% if form.quantity.errors %}
                        <div class="invalid-feedback">{{ form.quantity.errors|join:", " }}</div>
                    {% endif %}
                </div>

                <div class="col-md-2 mb-3 mx-auto" style="margin-top: 30px;">
                    <label for="{{ form.operatedate.id_for_label }}" class="form-label">操作日期<span class="text-danger">*</span></label>
                    <input type="date" name="{{ form.operatedate.name }}" id="{{ form.operatedate.id_for_label }}"
                           class="form-control {% if form.operatedate.errors %}is-invalid{% endif %}"
                           value="{% now 'Y-m-d' %}">
                    {% if form.operatedate.errors %}
                        <div class="invalid-feedback">{{ form.operatedate.errors|join:", " }}</div>
                    {% endif %}
                </div>
            

                <div class="col-md-2 mb-3 mx-auto" style="margin-top: 30px;">
                    <label for="{{ form.reason.id_for_label }}" class="form-label">
                        {{ form.reason.label }}<span class="text-danger">*</span>
                    </label>
                    <textarea name="{{ form.reason.name }}" id="{{ form.reason.id_for_label }}"
                              class="form-control {% if form.reason.errors %}is-invalid{% endif %}"
                              placeholder="出入库理由">{{ form.reason.value|default:'' }}</textarea>
                    {% if form.reason.errors %}
                    <div class="invalid-feedback">
                        {% for error in form.reason.errors %}
                            {{ error }}
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>
            </div>
                <!-- 调拨仓库字段 -->
                 
                <div class="col-md-3 mb-3" id="transfer_warehouse_group" style="display: none; margin-left: 100px; margin-top: 30px;">
                    <label for="{{ form.transfer_warehouse.id_for_label }}" class="form-label">
                        {{ form.transfer_warehouse.label }} <span class="text-danger">*</span>
                    </label>
                    <select name="{{ form.transfer_warehouse.name }}" id="{{ form.transfer_warehouse.id_for_label }}"
                            class="form-select {% if form.transfer_warehouse.errors %}is-invalid{% endif %}">
                        <option value="">-- 请选择调入仓库 --</option>
                        {% for choice in form.transfer_warehouse.field.choices %}
                            {% if choice.0 and choice.0 != warehouse.id %}
                                <option value="{{ choice.0 }}" {% if form.transfer_warehouse.value|stringformat:'s' == choice.0|stringformat:'s' %}selected{% endif %}>
                                    {{ choice.1 }}
                                </option>
                            {% endif %}
                        {% endfor %}
                    </select>
                    {% if form.transfer_warehouse.errors %}
                    <div class="invalid-feedback">
                        {% for error in form.transfer_warehouse.errors %}
                            {{ error }}
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>
            </div>

            <div class="text-center"  style="margin-top: 30px; margin-bottom: 60px;">
                <button type="submit" class="btn ms-2" style="background-color: #417690; color: white;">保 存</button>
            </div>
        </form>
    </div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const operateModeSelect = document.getElementById('{{ form.operatemode.id_for_label }}');
    const transferGroup = document.getElementById('transfer_warehouse_group');
    const quantityInput = document.getElementById('{{ form.quantity.id_for_label }}');
    const reasonInput = document.getElementById('{{ form.reason.id_for_label }}');
    const transferWarehouseSelect = document.getElementById('{{ form.transfer_warehouse.id_for_label }}');
    const recordForm = document.getElementById('recordForm');

    const outboundModes = [
        'maintain', 'write_off', 'transfer_out', 'project_out',
        'expired_out', 'damage_out', 'adjustment_out'
    ];

    const currentQuantity = parseInt(document.getElementById('current_quantity').textContent);

    // 切换调拨仓库显示
    function toggleTransferField() {
        if (operateModeSelect.value === 'transfer_out') {
            transferGroup.style.display = 'block';
        } else {
            transferGroup.style.display = 'none';
        }
    }

    operateModeSelect.addEventListener('change', toggleTransferField);
    toggleTransferField();  // 初始化判断一次

    // 表单提交前验证
    recordForm.addEventListener('submit', function (event) {
        let isValid = true;

        // 重置错误提示
        quantityInput.classList.remove('is-invalid');
        document.getElementById('quantity-error').textContent = '';
        reasonInput.classList.remove('is-invalid');

        const quantity = parseInt(quantityInput.value);
        const operateMode = operateModeSelect.value;
        const isOutbound = outboundModes.includes(operateMode);

        // 验证原因不能为空
        if (!reasonInput.value.trim()) {
            event.preventDefault();
            reasonInput.classList.add('is-invalid');
            reasonInput.nextElementSibling.textContent = '出入库原因不能为空';
            isValid = false;
        }

        // 验证数量是否为正数
        if (isNaN(quantity) || quantity <= 0) {
            event.preventDefault();
            quantityInput.classList.add('is-invalid');
            document.getElementById('quantity-error').textContent = '请输入大于0的数量';
            isValid = false;
        }

        // 出库数量不能超过库存
        if (isOutbound && quantity > currentQuantity) {
            event.preventDefault();
            quantityInput.classList.add('is-invalid');
            document.getElementById('quantity-error').textContent =
                '出库数量不能大于当前库存(' + currentQuantity + ')';
            isValid = false;
        }

        // 调拨必须选目标仓库
        if (operateMode === 'transfer_out' && !transferWarehouseSelect.value) {
            event.preventDefault();
            transferWarehouseSelect.classList.add('is-invalid');
            let feedback = transferWarehouseSelect.nextElementSibling;
            if (feedback && feedback.classList.contains('invalid-feedback')) {
                feedback.textContent = '调拨出库必须选择目标仓库';
            } else {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'invalid-feedback';
                errorDiv.textContent = '调拨出库必须选择目标仓库';
                transferWarehouseSelect.parentNode.appendChild(errorDiv);
            }
            isValid = false;
        }

        return isValid;
    });
});
</script>

{% endblock %}